<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\WeChat\WxTrait;
use App\Models\Demand;

use App\Models\Goods;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\MessageBag;
class DemandController extends Controller
{
    use ModelForm;
    use WxTrait;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('扫码失败的isbn');
            $content->description('处理扫码失败的isbn，处理成功后用户模板消息通知用户');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('扫码失败的isbn');
            $content->description('处理扫码失败的isbn，处理成功后用户模板消息通知用户');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('扫码失败的isbn');
            $content->description('处理扫码失败的isbn，处理成功后用户模板消息通知用户');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Demand::class, function (Grid $grid) {
            $grid->disableCreation();//禁用创建按钮
            $grid->actions(function ($actions) {
                $row=$actions->row;
                $goods=Goods::where('isbn13',$row->isbn)->orWhere('isbn10',$row->isbn)->first();
                if(!$goods || $row->is_dealed!=0){
                    //当前记录未处理，且数据库中已存在记录
                    $actions->disableEdit();
                }
            });
            $grid->model()->orderBy('is_dealed');//需要处理的排前面
            $grid->id('ID')->sortable();
            $grid->openid('openid');
            $grid->isbn('isbn');
            $grid->fail_id('发送失败的模板消息id');
            $grid->is_dealed('已处理')->display(function ($data){
                return $data?'是':'否';
            });
            $grid->send_user('已向该用户发送模板消息')->display(function ($data){
                return $data?'是':'否';
            });
            $grid->send_manager('已向管理员发送模板消息')->display(function ($data){
                return $data?'是':'否';
            });
            $grid->more('书籍名称')->display(function (){
                $goods=Goods::where('isbn13',$this->isbn)->orWhere('isbn10',$this->isbn)->first();
                return $goods?'<span style="color:green">'.$goods->title.'</span>':'不存在';
            });
            $grid->created_at('创建时间');
            $grid->updated_at('更新时间');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Demand::class, function (Form $form) {
            $form->display('openid','openid');
            $form->display('isbn','isbn');
            $form->radio('is_dealed','是否处理')->options(['0' => '否', '1'=> '是']);

            $form->saving(function ($form) {
                //检查当前处理状态
                if($form->model()->is_dealed==1){
                    $error = new MessageBag([
                        'title'   => '错误提示',
                        'message' => '当前记录已被处理，不可重复操作',
                    ]);
                    return back()->with(compact('error'));
                }
                if($form->is_dealed!=1){
                    $error = new MessageBag([
                        'title'   => '错误提示',
                        'message' => '没有选择处理',
                    ]);
                    return back()->with(compact('error'));
                }
                $isbn=$form->model()->isbn;
                //检查商品是否存在
                $goods=Goods::where('isbn13',$isbn)->orWhere('isbn10',$isbn)->first();
                if(!$goods){
                    $error = new MessageBag([
                        'title'   => '错误提示',
                        'message' => '未在平台中找到相关商品，禁止操作',
                    ]);
                    return back()->with(compact('error'));
                }
                //发送模板消息
                $openids=explode(',',$form->model()->openid);
                if(count($openids)==0){
                    $error = new MessageBag([
                        'title'   => '错误提示',
                        'message' => '没有需要发送模板消息的用户',
                    ]);
                    return back()->with(compact('error'));
                }
                $content=[
                    'first'=>'扫码失败的书籍处理通知',
                    'keyword1'=>'书籍信息',
                    'keyword2'=>'已增加',
                    'keyword3'=>'您扫码失败的书籍：《'.$goods->title.'》已添加到平台',
                    'remark'=>'点击进入您的书架，扫码上架吧！'
                ];
                $url=env('APP_URL').'/depot';
                foreach ($openids as $v){
                    if(!$v){
                        continue;
                    }
                    $res=$this->prepareMessage($v,2,$content,$url);
                    if(!$res['result']){
                        if($res['fail_id']){
                            $form->model()->fail_id.= $res['fail_id'].',';
                        }
                    }
                }
                if(!$form->model()->fail_id){
                    //不存在失败的记录
                    $form->model()->send_user=1;//已发送模板消息标识

                }
            });

        });
    }
}
